﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SHDocVw;
using WebBrowser = System.Windows.Controls.WebBrowser;

namespace Vkontakte.Api.Windows
{
	/// <summary>
	/// Interaction logic for Authorizator.xaml
	/// </summary>
	public partial class Authorizator
		: UserControl, IVkApiAutorizationMethod
	{
		private Session _session;

	//	private bool _comGetted = false;
	//	private SHDocVw.IWebBrowser2 _webBrowser2 = null;
		public Authorizator()
		{
			InitializeComponent();
		//	webBrowser.Navigating += new NavigatingCancelEventHandler(webBrowser_Navigating);
			webBrowser.Navigated += new NavigatedEventHandler(webBrowser_Navigated);
		}

		void webBrowser_Navigated(object sender, NavigationEventArgs e)
		{
			string url = e.Uri.ToString();
			Debug.WriteLine("Url={0}", url);
			if (url.StartsWith("http://vkontakte.ru/login.php?app"))
			{
				// Идет навигация
				return;
			}
			if (url.StartsWith("http://vkontakte.ru/api/login_success"))
			{
				IsAuthorized = true;
				_session = Session.GetFromUrl(url);

				//CookieContainer container = new CookieContainer();

				//foreach (string cookie in webBrowser.Document.Cookie.Split(';'))
				//{
				//    string name = cookie.Split('=')[0];
				//    string value = cookie.Substring(name.Length + 1);
				//    string path = "/";
				//    string domain = ".vkontakte.ru";
				//    container.Add(new Cookie(name.Trim(), value.Trim(), path, domain));
				//}
				//_session.Cookies = container;


			//	_session.Cookie = webBrowser.Document.Cookie;
				if (Authenticated != null)
				{
					Authenticated();
				}
				return;
			}
			if (url.StartsWith("http://login.vk.com/?vk="))
			{
				// Пользователь должен ввести пароль
				// Но это мы не обрабатываем 
				return;
			}
			if (url.StartsWith("http://vkontakte.ru/login.php?op=slogin&nonenone=1"))
			{
				if (NeedLoginData != null)
				{
					NeedLoginData();
				}
				return;
			}
			if (url.StartsWith("http://vkontakte.ru/login.php?op=slogin"))
			{
				return;
			}
			if (url.StartsWith("http://vkontakte.ru/login"))
			{
				if (NeedLoginData != null)
				{
					NeedLoginData();
				}
				return;
			}

			if (url.StartsWith("http://vkontakte.ru/api/login_failure"))
			{
				if (LoginCanceled != null)
				{
					LoginCanceled();
				}
			}
		}

		//void webBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
		//{
			//if (!_comGetted)
			//{
			//    Type webBrowserType = typeof(WebBrowser);

			//    FieldInfo field = webBrowserType.GetField("_axIWebBrowser2", BindingFlags.NonPublic | BindingFlags.Instance);
			//    _webBrowser2 = (SHDocVw.IWebBrowser2)field.GetValue(sender);
			//    SHDocVw.DWebBrowserEvents_Event wbEvents = (SHDocVw.DWebBrowserEvents_Event)_webBrowser2;
			//    wbEvents.BeforeNavigate += new DWebBrowserEvents_BeforeNavigateEventHandler(wbEvents_BeforeNavigate);
			//    wbEvents.NavigateComplete += new DWebBrowserEvents_NavigateCompleteEventHandler(NavigateCompleted);
			//    wbEvents.FrameNavigateComplete += new DWebBrowserEvents_FrameNavigateCompleteEventHandler(wbEvents_FrameNavigateComplete);
			//    _comGetted = true;
			//}
		//}

//        void wbEvents_BeforeNavigate(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Cancel)
//        {
//;
//        }

//        void wbEvents_FrameNavigateComplete(string URL)
//        {
	
//        }


//        private void NavigateCompleted(string url)
//        {
//            mshtml.IHTMLDocument2 doc = ( mshtml.IHTMLDocument2 ) webBrowser.Document;
//            foreach (var VARIABLE in doc.all)
//            {
//                object o = VARIABLE;
//            }
//        }


		public int AppID
		{
			get; set;
		}

		public ApplicationAccess ApplicationAccess
		{
			get; set;
		}

		public bool IsAuthorized
		{ get; private set;}
		

		public Session GetAuthorizationToken()
		{
			return _session;
		}

		public void Authenticate()
		{
			string url = Utils.GetLoginUri( AppID, ApplicationAccess );
			if (webBrowser.Dispatcher.CheckAccess())
			{
				webBrowser.Navigate(url);
			}else
			{
				webBrowser.Dispatcher.Invoke(new Action<string>(webBrowser.Navigate), url);
			}
	
		}

		public event Action NeedLoginData;

		public event Action Authenticated;

		public event Action LoginCanceled;
	}



	//[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	//[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
	//internal interface IServiceProvider
	//{
	//    [return: MarshalAs(UnmanagedType.IUnknown)]
	//    object QueryService(ref Guid guidService, ref Guid riid);
	//}

}
